package info.wegosoft.android.util;

import info.wegosoft.R;
import info.wegosoft.android.model.MBlog;
import info.wegosoft.android.model.Platform;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import android.content.Context;
import android.os.Environment;

/**  
 * Filename:    CacheUtil.java 
 * Package:     info.wegosoft.android.util 
 * Description: TODO(这里用一句话描述这个类的作用)
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-5-14 下午10:23:54  
 */
public class CacheUtil {

	public static List<MBlog> cacheMBlogList = new ArrayList<MBlog> ();
	
//	 /**
//	  * 从本地缓存xml中读取数据
//	  * @param context
//	  * @param platType
//	  * @throws Exception
//	  */
//	public static void readDateFromLocalXmlCache(Context context,int platformType) throws Exception{
//		cacheMBlogList.clear();
//		
//		FileInputStream fis = null;
//		
//		switch (platformType) {
//			case Platform.SINA_PLATFORM:
//				
//				 fis = context.openFileInput(context.getString(R.string.status_list_sina_xml_cache));
//				 
//				 transformDiffModelsToCommonModels(((Statuses) getXmlData(fis,platformType)).getStatuses(),platformType);
//				 
//				 break;
//			case Platform.TENCENT_PLATFORM:
//				
//				 fis = context.openFileInput(context.getString(R.string.status_list_tencent_xml_cache));
//				 			 
//				 transformDiffModelsToCommonModels(((Root) getXmlData(fis,platformType)).getData().getInfoList(),platformType);
//				 
//				 break;
//			default:
//				break;
//		}
//		
//	}
	
	/**
	 * 将新浪返回的json解析成list
	 */
	public static List<MBlog> transferSinaJSONStringToList(String jsonString) throws JSONException{
		
		JSONArray jsonArray = new JSONArray(jsonString);
		
		List<MBlog> list = new ArrayList<MBlog>();
		
		for(int i = 0;i < jsonArray.length();i++){
			 
			 JSONObject json = jsonArray.getJSONObject(i);
			 
			 MBlog sourceMblogBlog = null;
			 
			 if(!json.isNull("retweeted_status")){
				 sourceMblogBlog = transferSinaJSONObjectToMBlog(json.getJSONObject("retweeted_status"),null);
			 }
			 
			 MBlog mblog = transferSinaJSONObjectToMBlog(json,sourceMblogBlog);
			 
			 list.add(mblog);
		 }
		
		return list;
		
	}
	
	/**
	 * 将腾讯返回的jsonarray解析成list
	 */
	public static List<MBlog> transferTencentJSONStringToList(String jsonString) throws JSONException{
		
		//格式见http://open.t.qq.com/resource.php?i=1,1
		JSONArray jsonArray = new JSONObject(jsonString).getJSONObject("data").getJSONArray("info");
			
		List<MBlog> list = new ArrayList<MBlog>();
		
		for(int i = 0;i < jsonArray.length();i++){
			 
			 JSONObject json = jsonArray.getJSONObject(i);
			 
			 MBlog sourceMblogBlog = null;
			 
			 if(!json.isNull("source")){
				 sourceMblogBlog = transferTencentJSONObjectToMBlog(json.getJSONObject("source"),null);
			 }
			 
			 MBlog mblog = transferTencentJSONObjectToMBlog(json,sourceMblogBlog);
			 
			 list.add(mblog);
		}
		
		return list;
		
	}
	
	/**
	  * 从本地缓存json中读取数据
	  * @param context
	  * @param platType
	  * @throws Exception
	  */
	public static void readDateFromLocalJsonCache(Context context,int platformType) throws Exception{
		cacheMBlogList = new ArrayList<MBlog> ();
		
		FileInputStream fis = null;
		
		InputStreamReader isr = null; 
		
		BufferedReader br = null;  
		
		String line = null;  
	     
		StringBuilder sb = new StringBuilder();
		
		switch (platformType) {
			case Platform.SINA_PLATFORM:
				
				 fis = context.openFileInput(context.getString(R.string.status_list_json_cache) + "sina.json");
				 
				 isr = new InputStreamReader(fis); 
				 
				 br = new BufferedReader(isr);  
			      
				 while((line = br.readLine())!=null){  
			        	
					 sb.append(line);
					 
			     }  
					
				 cacheMBlogList = transferSinaJSONStringToList(sb.toString());
					
				 break;
			case Platform.TENCENT_PLATFORM:
				
				 fis = context.openFileInput(context.getString(R.string.status_list_json_cache) + "tencent.json");
				 	
				 isr = new InputStreamReader(fis); 
				 
				 br = new BufferedReader(isr);  
				 				
				 while((line = br.readLine())!=null){  
			        	
					 sb.append(line);
					 
			     }  
			     
				 cacheMBlogList = transferTencentJSONStringToList(sb.toString());
				 
				 break;
			default:
				break;
		}
		
	}
	
	/**
	 * 将服务器返回的tencent json状态转换为MBlog
	 * @param json
	 * @param sourceMBlog
	 * @return
	 * @throws JSONException
	 */
	private static MBlog transferTencentJSONObjectToMBlog(JSONObject json,MBlog sourceMBlog) throws JSONException{
		 MBlog mBlog = new MBlog();
		 
		 mBlog.setId(json.getString("id"));
		 
		 mBlog.setName(json.getString("name"));
		 
		 mBlog.setText(json.getString("text"));
	     
		 mBlog.setFrom(json.getString("from"));
		 
		 mBlog.setCreated_at(TimeUtil.formatTencentStringToDate(json.getString("timestamp")));
	     
		 if(!json.isNull("image") && !json.getString("image").trim().equals("")){
			 
			 //"image":["http://app.qpic.cn/mblogpic/ee666b466a23fa7bb8e8"]
			 String image = json.getString("image");
			 
//			 System.out.println(image);
			 
			 //这里去除方括号和双引号以后还要替换\,否则为http:\/\/app.qpic.cn\/mblogpic\/7479d62e022a11590a3e
			 image = image.substring(2, image.length()-2).replace("\\", "");
			 
//			 System.out.println(image);
			 
			 mBlog.setThumbnail_pic(image + "/120");
			 
			 mBlog.setBmiddle_pic(image + "/160");
			 
			 mBlog.setOriginal_pic(image + "/460");
			 
		 }
		 		
		 if(!json.isNull("uid"))
			 mBlog.setUser_id(json.getString("uid"));
		 
		 String head = json.getString("head");
		 
		 //有可能腾讯微博头像是默认的，此时mBlog.getHead()为空，就用默认的face
		 if(head!=null && !head.trim().equals(""))
			 mBlog.setHead(head + "/50" );
		 
		 mBlog.setScreen_name(json.getString("nick"));
		 
		 if(sourceMBlog!=null)
			 mBlog.setSourceMBlog(sourceMBlog);
		 
	     return mBlog;
	}
	
	/**
	 * 将服务器返回的sina json状态转换为MBlog
	 * @param json
	 * @param sourceMBlog
	 * @return
	 * @throws JSONException
	 */
	private static MBlog transferSinaJSONObjectToMBlog(JSONObject json,MBlog sourceMBlog) throws JSONException{
		 MBlog mBlog = new MBlog();
		 
		 mBlog.setId(json.getString("id"));
		 
		 mBlog.setText(json.getString("text"));
	     
		 mBlog.setFrom(json.getString("source"));
		 
		 if(!json.isNull("created_at"))
			 mBlog.setCreated_at(TimeUtil.formatSinaStringToDate(json.getString("created_at")));
	     
		 if(!json.isNull("thumbnail_pic")){
			 
			 mBlog.setThumbnail_pic(json.getString("thumbnail_pic"));
			 
			 mBlog.setBmiddle_pic(json.getString("bmiddle_pic"));
			 
			 mBlog.setOriginal_pic(json.getString("original_pic"));	 
			 
		 }
		 		
		 JSONObject user = json.getJSONObject("user");
		 
		 mBlog.setUser_id(user.getString("id"));
		 
		 mBlog.setHead(user.getString("profile_image_url"));
		 
		 mBlog.setScreen_name(user.getString("screen_name"));
		 
		 //注意新浪这里name就是screen_name
		 mBlog.setName(user.getString("screen_name"));
		 
		 if(sourceMBlog!=null)
			 mBlog.setSourceMBlog(sourceMBlog);
		 
	     return mBlog;
	}
	/**
	 * 将各个平台不同的MBlog转换为公用状态MBlog（仅xml时需要，json不需要）
	 */
//	private static void transformDiffModelsToCommonModels(List cacheDiffMBlogList,int platformType){
//		cacheMBlogList.clear();
//		
//		switch(platformType){
//		
//			case Platform.SINA_PLATFORM:
//				
//				 for(Object object:cacheDiffMBlogList){
//					 
//					 Status status = (Status) object;
//					 
//					 MBlog sourceMBlog = null;
//					 
//					 if(status.getRetweeted_status()!=null)
//					 	sourceMBlog = transformSinaStatus(status.getRetweeted_status(),null);
//						 
//					 MBlog mBlog = transformSinaStatus(status,sourceMBlog);
//					 
//					 cacheMBlogList.add(mBlog);
//				 }
//				 
//				 break;
//			case Platform.TENCENT_PLATFORM:
//				
//				 for(Object object:cacheDiffMBlogList){
//					 
//					 Info info = (Info) object;
//					 
//					 MBlog sourceMBlog = null;
//					 
//					 if(info.getSourceInfo()!=null)
//						 sourceMBlog = transformTencentStatus(info.getSourceInfo(),null);
//					 
//					 MBlog mBlog = transformTencentStatus(info,sourceMBlog);
//					 
//					 cacheMBlogList.add(mBlog);
//				 }
//				 
//				 break;
//			default:
//				 break;
//		}
//
//	}
	
	/**
	 * 将腾讯状态转换为公用状态（仅xml时需要，json不需要）
	 * @param info
	 * @param sourceMBlog
	 * @return
	 */
//	private static MBlog transformTencentStatus(Info info,MBlog sourceMBlog){
//		 MBlog mBlog = new MBlog();
//		 
//		 mBlog.setId(info.getId());
//		 
//		//时间戳,腾讯默认返回10位时间戳,如1305689517,不包括最后三位毫秒级别的,要在最后补上三个0再处理
//		 if(info.getTimestamp()!=null)
//			 mBlog.setCreated_at(TimeUtil.formatTencentStringToDate(info.getTimestamp() + "000"));
//		 
//		 mBlog.setText(info.getText());
//		 
//		 mBlog.setFrom(info.getFrom());
//		 
//		 if(info.getImage()!=null && !info.getImage().trim().equals(""))
//		 {
//			 mBlog.setThumbnail_pic(info.getImage() + "/120");
//			 
//			 mBlog.setBmiddle_pic(info.getImage() + "/160");
//			 
//			 mBlog.setOriginal_pic(info.getImage() + "/460");
//		 }	 
//		 
//		 mBlog.setUser_id(info.getName());
//		 
//		 mBlog.setHead(info.getHead() + "/50" );
//		 
//		 mBlog.setScreen_name(info.getNick());
//		 
//		 if(sourceMBlog!=null)
//			 mBlog.setSourceMBlog(sourceMBlog);
//		 
//		 return mBlog;
//	}
	
	/**
	 * 将新浪状态转换为公用状态（仅xml时需要，json不需要）
	 * @param status
	 * @param sourceMBlog
	 * @return
	 */
//	private static MBlog transformSinaStatus(Status status,MBlog sourceMBlog){
//		 MBlog mBlog = new MBlog();
//		 
//		 mBlog.setId(status.getId());
//		 
//		 mBlog.setCreated_at(TimeUtil.formatSinaStringToDate(status.getCreated_at()));
//		 
//		 mBlog.setText(status.getText());
//		 
//		 mBlog.setFrom(status.getSource());
//		 
//		 if(status.getThumbnail_pic()!=null && !status.getThumbnail_pic().trim().equals(""))
//		 {
//			 mBlog.setThumbnail_pic(status.getThumbnail_pic());
//			 
//			 mBlog.setBmiddle_pic(status.getBmiddle_pic());
//			 
//			 mBlog.setOriginal_pic(status.getThumbnail_pic());
//		 }
//		 
//		 mBlog.setUser_id(status.getUser().getId());
//		 
//		 mBlog.setHead(status.getUser().getProfile_image_url());
//		 
//		 mBlog.setScreen_name(status.getUser().getScreen_name());
//		 
//		 if(sourceMBlog!=null)
//			 mBlog.setSourceMBlog(sourceMBlog);
//		 
//		 return mBlog;
//	}
	
	/**
	 * 从服务器返回的xml或者本地xml cache读取状态数据
	 * @param is
	 * @return
	 * @throws Exception
	 */
//	public static Object getXmlData(InputStream is,int platformType) throws Exception{	
//		XMap xmap = new XMap();
//		
//		switch (platformType) {
//			case Platform.SINA_PLATFORM:
//				
//				 xmap.register(Statuses.class);
//				 
//				 break;
//			case Platform.TENCENT_PLATFORM:
//				
//				 xmap.register(Root.class);
//				 
//				 break;
//			default:
//				 break;
//		}
//		
//		
//		return xmap.loadAll(is)[0];
//	}
	
	/**
	 * 将服务器返回的xml缓存到本地程序私有文件夹内
	 * @param out
	 * @param urlInputStream
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 * @throws TransformerException
	 */
//	public static void saveURLXmlCache(FileOutputStream out,
//			InputStream urlInputStream) throws IOException, ParserConfigurationException, SAXException, TransformerException{
//		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
//				.newDocumentBuilder();
//		
//		Document doc = builder.parse(urlInputStream);
//		
//		TransformerFactory tfactory = TransformerFactory.newInstance();
//		
//		Transformer transformer = tfactory.newTransformer();
//		
//		StreamResult result = new StreamResult(out);
//		
//		DOMSource source = new DOMSource(doc);
//		
//		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//		
//		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
//		
//		transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
//		
//		transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
//		
//		transformer.transform(source, result);
//	}
	
	/**
	 * 将服务器返回的json缓存到本地程序私有文件夹内
	 * @param out
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 * @throws TransformerException
	 */
	public static void saveJsonCache(FileOutputStream out,
			InputStream urlInputStream) throws IOException, ParserConfigurationException, SAXException, TransformerException{
		 StringBuilder sb = new StringBuilder();
		 
		 String line;
		 
		 BufferedReader reader = new BufferedReader(new InputStreamReader(urlInputStream, "UTF-8"));

		 while ((line = reader.readLine()) != null) {

			sb.append(line).append("\n");
			
		 }
		 
		 out.write(sb.toString().getBytes());
	}
	
	/**
	 * 将服务器返回的json缓存到本地程序私有文件夹内
	 * @param out
	 * @param result
	 * @throws IOException
	 */
	public static void saveJsonCache(FileOutputStream out,
			String result) throws IOException{	 
		 out.write(result.getBytes());
	}
	
	/**
	 * 清理本地缓存
	 * @param platFormType
	 */
	public static void cleanLocalCache(Context context,int platformType){
		
		String addCacheFlag = "";
		
		switch(platformType){
		
			case Platform.SINA_PLATFORM:
				
				 addCacheFlag = "sina";
				 
				 break;
				 
			case Platform.TENCENT_PLATFORM:
				
				 addCacheFlag = "tencent";
				 
				 break;
				 
			default:
				
				 break;
		}
		
		//清理头像
		File faceDir = new File(Environment.getExternalStorageDirectory()
				+ context.getResources().getString(R.string.user_face_dir_path)
				+ addCacheFlag);
		
		if(faceDir.exists()){
			
			faceDir.delete();
			
			System.out.println("清理头像缓存");
			
		}
		
		//清理状态图片
		File picDir = new File(Environment.getExternalStorageDirectory()
				+ context.getResources().getString(
						R.string.mblog_images_dir_path) + addCacheFlag);
		
		if(picDir.exists()){
			
			picDir.delete();
			
			System.out.println("清理状态图片");
			
		}
		
		//清理拍照上传缓存
		File uploadDir = new File(Environment.getExternalStorageDirectory()
				+ context.getResources().getString(R.string.upload_camera_dir_path));
		
		if(uploadDir.exists()){
			
			uploadDir.delete();
			
			System.out.println("清理拍照上传缓存");
			
		}
		
		//清理缓存的json
		context.deleteFile(context.getResources().getString(R.string.status_list_json_cache) + addCacheFlag + ".json");
		
		System.out.println("清理缓存的json");
	}
}
